$(function () {

    var pID = parseInt(location.search.substring(1).split('=')[1]);
    // console.log(pID);
    var good = null;
    phoneData.forEach(e => {
        if (e.pID === pID) {
            good = e;
        }
    });

    if (!good) {
        alert('商品信息错误');
        location.href = './list.html';
    }

    var cartList = utils.getLocalDataArray('cartList');
    var count = 0;
    cartList.forEach(function (e, i) {
        count += e.number;
    });
    $('.shopcar>.count').text(count);


    $(".preview-img > img").attr('src', good.imgSrc);
    $(".sku-name").text(good.name);
    $(".summary-price").find('em').text('￥' + good.price);

    $('.choose-amount > .add').on('click', function () {
        var number = parseInt($('.choose-number').val());
        $('.choose-number').val(++number);
        if (number > 1) {
            $('.reduce').removeClass('disabled');
        }
    });

    $('.choose-amount > .reduce').on('click', function () {
        if ($(this).hasClass('disabled')) {
            return;
        }
        var number = parseInt($('.choose-number').val());
        $('.choose-number').val(--number);
        if (number <= 1) {
            $('.reduce').addClass('disabled');
        }
    });

    $('.choose-number').on('input', function () {
        var number = parseInt($(this).val());
        if (number > 1) {
            $('.reduce').removeClass('disabled');
        }
    });

    $(".addshopcar").on('click', function () {
        var isInCart = cartList.some((e, i) => {
            return e.pID === pID;
        })
        console.log(isInCart);
        var number = parseInt($('.choose-number').val());
        if (isInCart) {
            var temp = cartList.find(function (e) {
                return e.pID === pID;
            });
            temp.number += number;
        } else {
            good.number = number;
            cartList.push(good);
        }
        var json = JSON.stringify(cartList);
        localStorage.setItem('cartList', json);
        var count = 0;
        cartList.forEach(function (e) {
            count += e.number;
        });
        $('.shopcar>.count').text(count);

        location.href = './cart.html';
    });
});